/* eslint-disable no-unused-vars */
/* eslint-disable no-param-reassign */
/* eslint-disable no-new-func */
/* eslint-disable no-eval */
/* eslint-disable import/no-cycle */
import React from 'react';
import DesignUtil from '../common/DesignUtil';

class ControlPlus {
  static defaultToolBar = [
    {
      title: '基础控件',
      control: ['Text', 'Blank', 'Label', 'TextArea', 'Radio', 'CheckBox', 'Select', 'Date', 'Time', 'Button'],
    },
    {
      title: '高级控件',
      control: ['LiveCode', 'SubForm', 'AddSubForm', 'Echart', 'TableContainer'],
    },
    {
      title: '布局控件',
      control: ['FlexContainer', 'TabContainer'],
    },
  ];

  static getDefaultToolBar() {
    return ControlPlus.defaultToolBar;
  }

  static create(type) {
    return ControlPlus.create2(type, {});
  }

  static create2(type, props) {
    return ControlPlus.create3(type, props, {});
  }

  static create3(type, props, data) {
    return ControlPlus.create4(type, props, data, {});
  }

  static create4(type, props, data, extProps) {
    let typeControl = `${type}`;
    if (typeControl.indexOf('Control') <= -1) {
      typeControl += 'Control';
    }
    const context = require.context('./', true, /.(js)$/);
    const path = context(`./${typeControl}.js`);
    // const code = `new ${typeControl}(props,data,extProps)`;
    // const r = eval(code);
    try {
      const r = path.default.create(props, data, extProps);
      return r;
    } catch (e) {
      console.error(`模块加载失败:${typeControl}.js`);
      return null;
    }
  }

  // 根据旧表单元素转换成表单标准控件
  static createByOldFormChild(child, index) {
    const designtype = child.props.designtype || '';
    if (child.type.name === 'DesignControl') {
      const designtype2 = child.props.designtype || child.props.designdata?.type || '';
      const c = ControlPlus.create4(
        designtype2,
        { ...child.props, ...{ children: child.props.children } },
        child.props.designdata,
        child.props.extprops || child.props.extProps,
      );
      c.data.key = child.designkey || child.props.designkey;
      c.data.order = index;
      ControlPlus.checkOldFormChildKeyIsNotNull(c);
      return c;
    } else if (designtype === 'PlaceHolder') {
      const c = ControlPlus.create2('PlaceHolder', { children: child });
      c.data.key = child.designkey || child.props.designkey;
      c.data.order = index;
      ControlPlus.checkOldFormChildKeyIsNotNull(c);
      return c;
    } else {
      const c2 = ControlPlus.create2('None', { children: child });
      c2.data.key = child.designkey || child.props.designkey; // || c2.data.key
      c2.data.order = index;
      ControlPlus.checkOldFormChildKeyIsNotNull(c2);
      return c2;
    }
  }

  // 检查表单元素key是否为空,为空分配临时key,确保临时渲染
  static checkOldFormChildKeyIsNotNull(control) {
    if (control.data.key == null) {
      console.warn('检测到表单元素designkey为空,可能影响表单设计渲染', control);
      control.data.key = `tp${DesignUtil.UUID(16)}`; // 临时key
    }
  }
}

export default ControlPlus;
